<?php

namespace App\Http\Controllers;

use App\Events\BalanceChange;
use App\Events\BuyChange;
use App\Events\ProfileChange;
use App\Models\Buy;
use App\Models\User;
use Illuminate\Http\Request;

class OrderController extends Controller
{
    public function bySeller(Request $request)
    {
        if (sys('api_switch') == 0) {
            fail('API已关闭');
        }

        if (count($request->rows) > sys('api_order_max_rows_count')) {
            fail('提交数据过多');
        }

        $orders = $this->makeOrders($request->rows, '商户卖币(人工)');

        return success($orders);
    }

    public function sdk(Request $request)
    {
        if (sys('api_switch') == 0) {
            fail('API已关闭');
        }
        if (count($request->list) > sys('api_order_max_rows_count')) {
            fail('提交数据过多');
        }
        $seller = User::where('api_token', $request->token)->first();
        if (!$seller) {
            forbidden();
        }
        if (!$seller->enable) {
            fail('商户已禁用');
        }

        $ips = $seller->whitelist()->type('callback')->pluck('ip');
        if ($ips->count() === 0 || !$ips->contains($request->ip())) {
            fail('未设置白名单');
        }

        $request->validate([
            'token' => 'required',
            'list.*.bank' => 'required',
            'list.*.card' => 'required',
            'list.*.realname' => 'required',
            'list.*.coins' => 'required|integer',
            'list.*.transaction_id' => 'required|min:18|max:32|alpha_num|unique:buy',
            // 'list.*.callback_url' => 'url',
        ], [
            'list.*.coins.integer' => '请输入正确币值',
            'list.*.transaction_id.unique' => 'transaction_id 重复',
            'list.*.transaction_id.*' => '请输入18位 - 32位数字和字母格式',
        ]);

        $du = collect($request->list)->duplicates('transaction_id');
        //\Log::debug(json_encode($du));
        if ($du->count() > 0) {
            fail('transaction_id 重复');
        }

        auth()->login($seller);

        $orders = $this->makeOrders($request->list, '商户卖币(接口)');

        return success($orders);
    }

    /**
     * @param Request $request
     * 查询订单
     */
    protected function sdkOrderDetail(Request $request){
        if (sys('api_switch') == 0) {
            fail('API已关闭');
        }
        $seller = User::where('api_token', $request->token)->first();
        if (!$seller) {
            forbidden();
        }
        if (!$seller->enable) {
            fail('商户已禁用');
        }

        $ips = $seller->whitelist()->type('callback')->pluck('ip');
        if ($ips->count() === 0 || !$ips->contains($request->ip())) {
            fail('未设置白名单');
        }

        $request->validate([
            'token' => 'required',
            'list.*.id' => 'required',
            'list.*.transaction_id' => 'required',
        ], [
            'list.*.id' => '请输入订单返回时的id',
            'list.*.transaction_id' => '请输入商户订单号 transaction_id',
        ]);

        $buys = Buy::selectRaw(implode(',', [
            'id as system_id',
            'transaction_id',
            'CASE WHEN state = "waiting" or state = "took" THEN "待处理" WHEN state = "frozen" or state = "unfreeze" or state = "fail" THEN "已完成" END as state',
            'bank',
            'bankcard',
            'realname',
            'fee',
            'tip',
            'created_at',
            'updated_at'
        ]))
            ->where('seller_id', $seller->id)
            ->where('id',$request->list[0]['id'])
            ->where('transaction_id',$request->list[0]['transaction_id'])
            ->first();
        if (!$buys) {
            fail('订单不存在');
        }

        return success($buys);
    }

    protected function makeOrders($arr, $type)
    {
        $rows = collect($arr);
        $seller = seller();

        $rows->map(function ($row) {
            $min = sys('buy_min_coins');
            if ($min > $row['coins']) {
                fail('单笔币值太小');
            }
        });

        [$total, $fee, $tip] = $seller->calcOrder($rows->sum('coins'));
        if ($total > $seller->coins) {
            fail("FCB不足，剩余{$seller->coins}");
        }
        $orders = \DB::transaction(function () use ($rows, $seller, $type) {
            return $rows->map(function ($row) use ($seller, $type) {
                $buy = Buy::create([
                    'id' => app('snowflake')->id(),
                    'seller_id' => $seller->id,
                    'bank' => $row['bank'],
                    'bankcard' => $row['card'],
                    'realname' => $row['realname'],
                    'coins' => $row['coins'],
                    'seller_fee' => bcmul($row['coins'], $seller->fee_ratio, 3),
                    'seller_tip' => $seller->tip,
                    'transaction_id' => $row['transaction_id'] ?? null,
                    'created_at' => now()
                ]);

                $seller->coinsChange(-$buy->coins, $type, $buy->id);
                $seller->coinsChange(-$buy->seller_fee, '商户卖币手续费', $buy->id);
                $seller->coinsChange(-$buy->seller_tip, '商户卖币扣奖励', $buy->id);
                
                event(new BuyChange($seller->id, 'add', $buy->id));

                return $buy->only('id', 'transaction_id', 'bank', 'bankcard', 'realname', 'coins', 'seller_fee', 'seller_tip', 'created_at');
            });
        });
        event(new ProfileChange($seller->id));
        event(new BalanceChange($seller->id));

        return $orders;
    }
}
